#include <iostream>
#include <unistd.h>
#include <fcntl.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl");
        exit(1);
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    SetNonBlock(0);
    char buff[1024];
    while (true)
    {
        ssize_t n = read(0, buff, sizeof(buff) - 1);
        if (n > 0)
        {
            buff[n - 1] = 0;
            std::cout << buff << std::endl;
        }
        else if (n <= 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "非阻塞调用,资源未就绪" << std::endl;
                sleep(1);
                continue;
            }
            else if (errno == EINTR)
            {
                continue;
            }
        }
        else if (n == 0)
        {
            break;
        }
        sleep(1);
        std::cout << "n: " << n << std::endl;
    }
    return 0;
}